package com.pvj.myaccount.adapter

import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.pvj.myaccount.R
import com.pvj.myaccount.room.entity.Cost
import com.pvj.myaccount.uitls.TimeUtil


class TodayAdapter(private val context: Context) :
    BaseAdapter() {
    private var items: List<Cost>? = listOf()

    fun update(items: List<Cost>?) {
        this.items = items
        notifyDataSetChanged()
    }

    override fun getCount(): Int {
        return items?.size ?: 0
    }

    override fun getItem(position: Int): Cost? {
        return items?.get(position)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val inflater = LayoutInflater.from(context)
        var view = convertView
        val holder: ViewHolder

        if (view == null) {
            // 如果convertView为null，说明没有可复用的view，需要inflate新的view
            view = inflater.inflate(R.layout.today_item, parent, false)
            holder = ViewHolder(view)
            view.tag = holder
        } else {
            // 如果convertView不为null，说明有可复用的view，可以直接使用
            holder = view.tag as ViewHolder
        }

        val item = items?.get(position)
        if (item != null) {
            holder.nameTextView.text = item.name
            holder.moneyTextView.text = item.money.toString()
            holder.timeTextView.text = TimeUtil.timestampToBeijingStr(item.eventTime)
        }

        return holder.view
    }

    // 内部类，用于持有ListView中每一项的视图元素
    inner class ViewHolder(val view: View) {

        val nameTextView: TextView = view.findViewById(R.id.nameTextView)
        val moneyTextView: TextView = view.findViewById(R.id.moneyTextView)
        val timeTextView: TextView = view.findViewById(R.id.timeTextView)
    }
}